package com.taichuan.selfcheck.ui.fragment;

import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.g3288.g3288board.Rk3399GpioActionDefine;
import com.g3288.g3288board.TcRk3399GpioClient;
import com.orhanobut.logger.Logger;
import com.taichuan.keysupport.Key;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.eventbus.Serial485DataEvent;
import com.taichuan.selfcheck.eventbus.SwipeCardEvent;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.serialcommunication.SerialPortPublic;
import com.taichuan.serialcommunication.entity.SerialPortInfo;
import com.taichuan.tcutils.HexUtils;
import com.taichuan.tcutils.taichuan.SystemUtils;
import com.taichuan.tcutils.taichuan.TcDeviceType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2019/12/5
 */
public class CardFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {

    @BindView(R.id.fragment_card_card_textView)
    TextView cardTv;
    @BindView(R.id.fragment_card_card_isOutput_textView)
    TextView cardIsOutputTv;

    ResultDialog resultDialog;
    @BindView(R.id.fragment_card_card_offline_card_textView)
    TextView offlineCardResultTv;
    @BindView(R.id.fragment_card_485_data_textView)
    TextView dataFor485Tv;
    @BindView(R.id.fragment_card_485_card_data_textView)
    TextView cardDataFor485Tv;
    @BindView(R.id.fragment_card_485_serial_port_info_textView)
    TextView serialPort485InfoTv;
    @BindView(R.id.fragment_card_485_send_test_button)
    Button send485TestDataBtn;
    @BindView(R.id.fragment_card_485_mode_change_button)
    Button mode485ChangeBtn;
    @BindView(R.id.fragment_card_485_mode_change_layout)
    LinearLayout mode485ChangeLayout;
    @BindView(R.id.cardScrollView)
    ScrollView mCardScrollView;
    @BindView(R.id.tips_textView)
    TextView tipsTv;

    private int curScrollDistance;//ScrollView当前滑动的距离
    private final static int SCROLL_UP = 1;
    private final static int SCROLL_DOWN = 2;
    private final String TAG = getClass().getSimpleName();

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        resultDialog.show();
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_card;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        EventBus.getDefault().register(this);
        tipsTv.setText(Html.fromHtml(getString(R.string.ctrl_tips_card_test)));
        //显示485信息
        SerialPortInfo serialPortInfo = SerialPortPublic.get485SerialPortInfo();
        serialPort485InfoTv.setText("485串口库路径： " + serialPortInfo.getSerialPortPath() + " | 波特率： " + serialPortInfo.getSerialPortBaudrate());

        if (SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_VERTICAL_TOUCH_O8A_DOOR){
            mode485ChangeLayout.setVisibility(View.VISIBLE);
            mode485ChangeBtn.setTag("close");
        }

        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_7, getResources().getString(R.string.swipecard), getContext());       //设置弹窗发送的事件——刷卡测试
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //将TC-Y9D-O8A设备的485使用模式改为接收模式
        if (SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_VERTICAL_TOUCH_O8A_DOOR){
            TcRk3399GpioClient.getInstance().controlGpio(Rk3399GpioActionDefine.CHANGE_TC_Y9D_O8A_485_RECEIVE_MODE);
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (resultDialog.isShowing()) {
            resultDialog.dispatchKeyEvent(event);
        } if (event.getKeyCode() == Key.Convert.KEYCODE_JING) {     //按# 号键
            sendTest485Data();
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_2) {   //向上滑动
            scrollUIView(SCROLL_UP);
            return true;
        } else if (event.getKeyCode() == Key.Convert.KEYCODE_8) {   //向下滑动
            scrollUIView(SCROLL_DOWN);
            return true;
        }else if(event.getKeyCode() == Key.Convert.KEYCODE_5){
            change485Mode();
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 根据滑动类型进行页面滑动
     */
    public void scrollUIView(int scrollType) {
        //计算可滑动的最大距离
        int scrollMaxDistance = mCardScrollView.getChildAt(0).getHeight() - mCardScrollView.getMeasuredHeight();
        if (scrollType == SCROLL_UP) {
            if (curScrollDistance > 0) {
                curScrollDistance = curScrollDistance - mCardScrollView.getMeasuredHeight() / 2;//每次滑动控件的1/2高度距离
                mCardScrollView.scrollTo(0, curScrollDistance);
            } else {
                curScrollDistance = 0;
                Logger.t(TAG).e("已到顶部，无需滑动:");
            }
        } else {
            if (curScrollDistance <= scrollMaxDistance) {
                curScrollDistance = curScrollDistance + mCardScrollView.getMeasuredHeight() / 2;//每次滑动控件的1/2高度距离
                mCardScrollView.scrollTo(0, curScrollDistance);
                Logger.t(TAG).e("about_scroll滑动距离:" + curScrollDistance + "  滑动最大距离:" + scrollMaxDistance);
            } else {
                curScrollDistance = scrollMaxDistance;
                Logger.t(TAG).e("已到底部，无需滑动:");
            }
        }
    }

    /**
     * 定义一个EventBus 接收方法用于接收 刷卡 状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveCardEvent(SwipeCardEvent swipeCardEvent) {
        if (cardTv != null && cardIsOutputTv != null) {
            cardTv.setText(swipeCardEvent.getCardNum());
            cardIsOutputTv.setText(swipeCardEvent.isOut() ? "是" : "否");

            if (SystemUtils.isSupportMcuOffline()) {
                boolean isOfflineMatch = false;
                if (swipeCardEvent.getCardNum().endsWith("01")) {
                    isOfflineMatch = true;
                }
                offlineCardResultTv.setText(isOfflineMatch ? "匹配成功" : "匹配失败");
            } else {
                offlineCardResultTv.setText("无此功能");
            }
        }
    }

    /**
     * 定义一个EventBus 接收方法用于接收 485刷卡数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveSerial485DataEvent(Serial485DataEvent event) {
        if (dataFor485Tv != null && cardDataFor485Tv != null) {
            dataFor485Tv.setText(HexUtils.getFormatHex(event.getSrcData()));
            cardDataFor485Tv.setText(event.getStandardCard());
        }
    }

    @OnClick({R.id.fragment_card_485_send_test_button, R.id.fragment_card_485_mode_change_button})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.fragment_card_485_send_test_button: {
                sendTest485Data();
                break;
            }
            case R.id.fragment_card_485_mode_change_button: {
                change485Mode();
                break;
            }
        }
    }

    private void change485Mode() {
        if (SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_VERTICAL_TOUCH_O8A_DOOR){
            if (mode485ChangeBtn.getTag().equals("close")) {
                //切换为 485发送模式
                TcRk3399GpioClient.getInstance().controlGpio(Rk3399GpioActionDefine.CHANGE_TC_Y9D_O8A_485_SEND_MODE);
                mode485ChangeBtn.setTag("open");
                mode485ChangeBtn.setText(getStrById(R.string.change_485_mode_send_mode));
                showMsg("开启485【发送】模式");
            } else {
                //切换为 485接收模式
                TcRk3399GpioClient.getInstance().controlGpio(Rk3399GpioActionDefine.CHANGE_TC_Y9D_O8A_485_RECEIVE_MODE);
                mode485ChangeBtn.setTag("close");
                mode485ChangeBtn.setText(getStrById(R.string.change_485_mode_receive_mode));
                showMsg("开启485【接收】模式");
            }
        }else {
            showMsg("该机型不允许使用该功能");
        }
    }

    private void sendTest485Data() {
        //构建测试数据
        byte[] testData = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
                0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
        SerialPortPublic.send485Data(testData);
        showMsg("发送测试数据给Arm 485 成功");
    }

    @Override
    protected EmptyPresenter createPresenter() {
        return new EmptyPresenter();
    }



}
